<?php
namespace app\api\controller\cost;
use think\File;
use think\facade\Env;
use app\common\model\user\User as UserModel;
use app\common\model\company\Company;
use app\common\model\orderdata\Goods;
use app\common\model\quotation\QuotationList;
use app\common\model\orderhawa\HawaList;
use app\api\controller\Base;
use app\common\model\user\User;
use app\common\model\cost\Costtype;
use app\common\model\cost\Pay;
use app\common\model\cost\Revenue;
use app\common\model\company\Contract;
use app\common\model\cost\Costjournal;
use app\common\model\orderdelivery\DeliveryList;
use app\common\model\orderreceipt\ReceiptList;
use app\common\model\power\Rolepower;
class Costacco extends Base
{
	/**
	 * 初始化
	 */
    public function initialize(){
		parent::initialize();
		self::is_login();
		Rolepower::powerguard(203004);
	}
	
	/**
	 * 获取创建用户费用申报信息
	 * @return [type] [description]
	 */
	public function getcreateinfo(){
		$id = input('id');
		$type = input('type');
		if(!empty($id)){
			if(empty($type)){
				return myerr('缺少参数');
			}
			switch ($type) {
				case 'hawa':
					$data['costtypelist'] = Costtype::getlist('accocreate','orderhawa');
					$sb = HawaList::getinfo($id,'acco');
					$data['orderinfo']['title'] = '产废订单';
					$list[] = ['show'=>'公司名称','text'=>$sb['msg']['companyinfo']['Name']];
					$list[] = ['show'=>'下单时间','text'=>$sb['msg']['UpTime']];
					$list[] = ['show'=>'收集员姓名','text'=>$sb['msg']['buss']['UserName']];
					$list[] = ['show'=>'浮差金额','text'=>$sb['msg']['FloatingCost']];
					$list[] = ['show'=>'合计金额','text'=>$sb['msg']['TotalCost']];
					break;
				case 'receipt':
					$data['costtypelist'] = Costtype::getlist('accocreate','orderreceipt');
					$sb = ReceiptList::getinfo($id,'acco');
					$data['orderinfo']['title'] = '入库订单';
					$list[] = ['show'=>'库管姓名','text'=>$sb['msg']['ware']['Name']];
					$list[] = ['show'=>'入库时间','text'=>$sb['msg']['WarehouseTime']];
					$list[] = ['show'=>'收集员姓名','text'=>$sb['msg']['buss']['UserName']];
					$list[] = ['show'=>'浮差金额','text'=>$sb['msg']['FloatingCost']];
					$list[] = ['show'=>'合计金额','text'=>$sb['msg']['TotalCost']];
					break;
				case 'delivery':
					$data['costtypelist'] = Costtype::getlist('accocreate','orderdelivery');
					$sb = DeliveryList::getinfo($id,'acco');
					$data['orderinfo']['title'] = '出库订单';
					$list[] = ['show'=>'库管姓名','text'=>$sb['msg']['ware']['Name']];
					$list[] = ['show'=>'提单时间','text'=>$sb['msg']['UpTime']];
					$list[] = ['show'=>'出库时间','text'=>$sb['msg']['WarehouseTime']];
					$list[] = ['show'=>'处置单位','text'=>$sb['msg']['disp']['DisposalSiteName']];
					$list[] = ['show'=>'提单备注','text'=>$sb['msg']['UpNote']];
					if(!empty($sb['msg']['FloatingCost'])){
						$list[] = ['show'=>'浮差金额','text'=>$sb['msg']['FloatingCost']];
					}
					if(!empty($sb['msg']['TotalCost'])){
						$list[] = ['show'=>'合计金额','text'=>$sb['msg']['TotalCost']];
					}
					break;
				case 'contract':
					$data['costtypelist'] = Costtype::getlist('accocreate','contract');
					$data['orderinfo']['title'] = '合同订单';
					$sb = Contract::getinfo($id,'acco');
					$list[] = ['show'=>'公司名称','text'=>$sb['msg']['companyinfo']['Name']];
					$list[] = ['show'=>'合同编号','text'=>$sb['msg']['OrderNumber']];
					$list[] = ['show'=>'创建时间','text'=>$sb['msg']['CreateTime']];
					$list[] = ['show'=>'收集员姓名','text'=>$sb['msg']['buss']['Name']];
					$list[] = ['show'=>'合同费用','text'=>$sb['msg']['ContractCost']];
					$list[] = ['show'=>'合同期限','text'=>$sb['msg']['StartTime'].'~'.$sb['msg']['EndTime']];
					break;
				default:
					return myerr('参数错误');
					break;
			}
			$data['orderinfo']['list'] = $list;

		}else{
			$data['userlist'] = User::getcostuserlist();
			$data['rolelist'] = getrolename();
			$data['costtypelist'] = Costtype::getlist('accocreate');
		}
		return myok($data);
	}

	/**
	 * 创建财务
	 * @return [type] [description]
	 */
	public function create(){
		$data = input('post.');
		if(empty($data['PayCost'])||empty($data['TypeId'])||empty($data['Type'])){
			return myerr('缺少参数');
		}
		if($data['Type']=='revenue'){
			$sb = Revenue::screate($data);
		}elseif($data['Type']=='pay'){
			$sb = Pay::screate($data);
		}else{
			return myerr('参数错误');
		}
		return  myok($sb['msg']);
	}

	/**
	 * 获取订单的详细财务信息
	 * @param  string $id        [订单id]
	 * @param  string $type      订单类型
	 * @param  [type] $powertype 操作权限 mana/acco/buss/hawa
	 * @return [type]            [description]
	 */
	public function getorderinfo($id='',$type=''){
		if(empty($id)||empty($type)){
			return serr('缺少参数，请重新尝试');
		}
		$type_id = Costtype::getid($type);
		$rdata = [];
		$rdata['where'] = [['type_id',$type_id],['RelationListId',$id]];
		// $rdata['Type'] = 'cost';
		$rdata['pay'] = Pay::usergetlist($rdata,'acco',false);
		$rdata['revenue'] = Pay::usergetlist($rdata,'acco',false);
		return sok($rdata);
	}
	
	/**
	 * 获取订单信息
	 * @return [type] [description]
	 */
	public function delete(){
		$id = input('id');
		$type = input('type');
		if(empty($id)||empty($type)){
			return myerr('缺少参数，请重新尝试');
		}
		if($type=='pay'){
			$data = Pay::get($id);
		}else if($type=='revenue'){
			$data = Revenue::get($id);
		}
		if(empty($data)){
			return myerr('没找到您需要的信息');
		}
		if($data['State']!==Revenue::STATEOK){
			return myerr('订单状态有误，无法调整');
		}
		$ndata['id'] = $id;
		$ndata['State'] = Revenue::STATENO;
		if($type=='pay'){
			$sb = Pay::user_reinfo($ndata);
		}else if($type=='revenue'){
			$sb = Revenue::user_reinfo($ndata);
		}
		return myok('废弃成功');
	}
	
	/**
	 * 由于收集员修改订单
	 * 需要用户进行二次确认
	 * @return [type] [description]
	 */
	public function confirmorder(){
		$data = input('post.');
		$order = HawaList::get($data['id']);
        if(empty($order)||$order->State==HawaList::STATEDELETE){
        	return myerr('没有找到您需要的订单');
        }
        if($order->State!==HawaList::STATEWAITOK&&$order->State!==HawaList::STATETRANSPORT){
        	return myerr('订单状态无法确认');
        }
        if($order->ConfirmState!==HawaList::CONFRIMBUSS){
        	return myerr('订单状态无法确认');
        }
        $order->State = HawaList::STATETRANSPORT;
        $order->ConfirmState = HawaList::CONFRIMBUSS+HawaList::CONFRIMHAWA;
        $order->save();
        return myok('订单确认成功');
	}
	/**
	 * 图片上传
	 * @return [type] [description]
	 */
	public function upimg(){
		$type = empty(input('type'))?'other':input('type');
		if(!$type=='user'||!$type=='buss'||!$type=='acco'){
			$type = 'other';
		}
		try {
			$file = request()->file('img');
		} catch (\Exception $e) {
			return json_encode(['status'=>'error','data'=>$e->getMessage()]);
		}
        // 移动到框架应用根目录/public/uploads/ 目录下
        if(!is_null($file)){
           	try{
           		$save_path = Env::get('root_path').'public\\static' .'\\upimg\\cost\\'.$type.'\\';
	            $info = $file->validate(["size"=>50000000,'ext'=>'jpg,png,gif'])->rule("date")->move($save_path);
	            //echo $save_path. DS . date("Ymd") . DS .  $info->getFilename();
	            $image = \think\Image::open($save_path . '\\' . $info->getSaveName());  
	            $image->thumb(2000, 2000)->save($save_path .  '\\' . $info->getSaveName());  
	            if($info){//getSaveName();
	                $p=$info->getFilename();
	                return json_encode(['status'=>'ok','data'=>SERVERURL.'static/upimg/cost/'.$type.'/'.date('Ymd',time()).'/'.$p]);
	            }else{
	              return json_encode(['status'=>'error','data'=>$info->getError()]);
	            }
           	} catch (\Exception $e) {
				return json_encode(['status'=>'error','data'=>$e->getMessage()]);
			}	
            
         }else{
              return json_encode(['status'=>'error','data'=>'没有找到需要上传的图片']);
         }
	}


	/**
	 * 判断账号是否登录
	 * @return boolean [description]
	 */
	private function is_login(){
		$data = UserModel::is_sessionlogin();
		if (!$data['code']) {
			$data['options'] = 'relogin';
			json($data)->send();
			exit;
		}
	}
}
